package top.yokey.shopai.main.fragment;

import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;

import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.AppCompatTextView;
import androidx.recyclerview.widget.RecyclerView;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.zxing.client.android.MNScanManager;
import com.google.zxing.client.android.model.MNScanConfig;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Objects;

import top.yokey.shopai.R;
import top.yokey.shopai.main.adapter.MainSearchKeyAdapter;
import top.yokey.shopai.main.viewmodel.MainSearchVM;
import top.yokey.shopai.zcom.App;
import top.yokey.shopai.zcom.base.BaseFragment;
import top.yokey.shopai.zcom.help.SharedHelp;
import top.yokey.shopai.zcom.help.ToastHelp;
import top.yokey.shopai.zcom.other.Constant;
import top.yokey.shopai.zcom.recycler.FlowLayoutManager;
import top.yokey.shopai.zcom.recycler.SpaceDecoration;
import top.yokey.shopai.zcom.util.VerifyUtil;
import top.yokey.shopai.zcom.voice.XFVoiceDialog;
import top.yokey.shopai.zsdk.data.GoodsSearchData;

public class MainSearchFragment extends BaseFragment {

    private final GoodsSearchData data = new GoodsSearchData();
    private final ArrayList<String> arrayList = new ArrayList<>();
    private final MainSearchKeyAdapter adapter = new MainSearchKeyAdapter(arrayList);
    private final ArrayList<String> hotArrayList = new ArrayList<>();
    private final MainSearchKeyAdapter hotAdapter = new MainSearchKeyAdapter(hotArrayList);
    private AppCompatEditText searchEditText = null;
    private AppCompatImageView scanImageView = null;
    private AppCompatImageView searchImageView = null;
    private AppCompatImageView clearImageView = null;
    private AppCompatTextView recentTextView = null;
    private RecyclerView recentRecyclerView = null;
    private AppCompatTextView hotTextView = null;
    private RecyclerView hotRecyclerView = null;
    private FloatingActionButton voiceButton = null;
    private MainSearchVM vm = null;

    @Override
    public View initView() {

        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_main_search, null);
        searchEditText = view.findViewById(R.id.searchEditText);
        scanImageView = view.findViewById(R.id.scanImageView);
        searchImageView = view.findViewById(R.id.searchImageView);
        clearImageView = view.findViewById(R.id.clearImageView);
        recentTextView = view.findViewById(R.id.recentTextView);
        recentRecyclerView = view.findViewById(R.id.recentRecyclerView);
        hotTextView = view.findViewById(R.id.hotTextView);
        hotRecyclerView = view.findViewById(R.id.hotRecyclerView);
        voiceButton = view.findViewById(R.id.voiceButton);
        return view;

    }

    @Override
    public void initData() {

        searchEditText.setHint(R.string.tipsSearchHint);
        App.get().setRecyclerView(recentRecyclerView, adapter);
        recentRecyclerView.setLayoutManager(new FlowLayoutManager());
        recentRecyclerView.addItemDecoration(new SpaceDecoration(App.get().dp2Px(4)));
        App.get().setRecyclerView(hotRecyclerView, hotAdapter);
        hotRecyclerView.setLayoutManager(new FlowLayoutManager());
        hotRecyclerView.addItemDecoration(new SpaceDecoration(App.get().dp2Px(4)));
        vm = getVM(MainSearchVM.class);
        vm.getSearch();

    }

    @Override
    public void initEvent() {

        searchEditText.setOnEditorActionListener((textView, i, keyEvent) -> {
            if (i == EditorInfo.IME_ACTION_SEARCH) {
                data.setKeyword(Objects.requireNonNull(searchEditText.getText()).toString());
                gotoList();
            }
            return false;
        });

        scanImageView.setOnClickListener(view -> {
            MNScanConfig scanConfig = new MNScanConfig.Builder()
                    .isShowVibrate(false)
                    .isShowBeep(true)
                    .isShowPhotoAlbum(true)
                    .setScanHintText(getString(R.string.qrCodeScan))
                    .setZoomControllerLocation(MNScanConfig.ZoomControllerLocation.Bottom)
                    .isShowZoomController(true)
                    .builder();
            MNScanManager.startScan(requireActivity(), scanConfig, (code, data) -> {
                switch (code) {
                    case MNScanManager.RESULT_SUCCESS:
                        String result = data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS);
                        if (result.contains(Constant.URL)) {
                            App.get().startUrl(result);
                            return;
                        }
                        ToastHelp.get().show(data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_SUCCESS));
                    case MNScanManager.RESULT_FAIL:
                        ToastHelp.get().show(data.getStringExtra(MNScanManager.INTENT_KEY_RESULT_ERROR));
                        break;
                }
            });
        });

        searchImageView.setOnClickListener(view -> {
            data.setKeyword(Objects.requireNonNull(searchEditText.getText()).toString());
            gotoList();
        });

        clearImageView.setOnClickListener(view -> {
            SharedHelp.get().putString(Constant.SHARED_SEARCH_KEYWORD, "");
            recentTextView.setVisibility(View.GONE);
            clearImageView.setVisibility(View.GONE);
            recentRecyclerView.setVisibility(View.GONE);
        });

        adapter.setOnItemClickListener((position, bean) -> {
            data.setKeyword(bean);
            gotoList();
        });

        hotAdapter.setOnItemClickListener((position, bean) -> {
            data.setKeyword(bean);
            gotoList();
        });

        voiceButton.setOnClickListener(view -> XFVoiceDialog.get().show(getActivity(), result -> {
            if (!VerifyUtil.isEmpty(result)) {
                data.setKeyword(result);
                gotoList();
            }
        }));

    }

    @Override
    public void initObserve() {

        vm.getSearchLiveData().observe(this, bean -> {
            hotArrayList.clear();
            hotArrayList.addAll(bean.getList());
            hotAdapter.notifyDataSetChanged();
            if (hotArrayList.size() == 0) {
                hotTextView.setVisibility(View.GONE);
                hotRecyclerView.setVisibility(View.GONE);
            } else {
                hotTextView.setVisibility(View.VISIBLE);
                hotRecyclerView.setVisibility(View.VISIBLE);
            }
        });

        vm.getErrorLiveData().observe(this, bean -> {
            hotTextView.setVisibility(View.GONE);
            hotRecyclerView.setVisibility(View.GONE);
        });

    }

    @Override
    public void onResume() {

        super.onResume();
        arrayList.clear();
        String searchKeyword = SharedHelp.get().getString(Constant.SHARED_SEARCH_KEYWORD);
        clearImageView.setVisibility(VerifyUtil.isEmpty(searchKeyword) ? View.GONE : View.VISIBLE);
        recentTextView.setVisibility(VerifyUtil.isEmpty(searchKeyword) ? View.GONE : View.VISIBLE);
        recentRecyclerView.setVisibility(VerifyUtil.isEmpty(searchKeyword) ? View.GONE : View.VISIBLE);
        if (!VerifyUtil.isEmpty(searchKeyword)) {
            String[] keyArray = searchKeyword.split(",");
            Collections.addAll(arrayList, keyArray);
            adapter.notifyDataSetChanged();
        }

    }

    //自定义方法

    private void gotoList() {

        String keyword = data.getKeyword();
        if (!VerifyUtil.isEmpty(keyword)) {
            String searchKey = SharedHelp.get().getString(Constant.SHARED_SEARCH_KEYWORD);
            if (VerifyUtil.isEmpty(searchKey)) {
                searchKey = keyword;
            } else if (!searchKey.contains(",")) {
                if (!searchKey.equals(keyword)) {
                    searchKey += "," + keyword;
                }
            } else {
                if (!searchKey.contains("," + keyword + ",") && !searchKey.contains("," + keyword) && !searchKey.contains(keyword + ",")) {
                    searchKey += "," + keyword;
                }
            }
            SharedHelp.get().putString(Constant.SHARED_SEARCH_KEYWORD, searchKey);
        }
        App.get().startGoodsList(data);
        searchEditText.setText("");

    }

}
